
#include "stdafx.h"
#include "Data/DataLua.h"
#include "Data/DataImp.h"
#include "DataManagerLua.h"

namespace DataManagerLua
{

bool push(lua_State* L, IDataManager* pDataMgr)
{
	IDataManager** pp = (IDataManager**)lua_newuserdata(L, sizeof(IDataManager*));
	*pp = pDataMgr;
	luaL_getmetatable(L, "woe.datamgr");
	if (lua_istable(L, -1))
	{
		lua_setmetatable(L, -2);
		return true;
	}
	else
	{
		LOG_ERROR("Failed to push IDataManagerObject to lua, metatable not found!");
		return false;
	}
}

IDataManager* getUserData(lua_State* L)
{
	IDataManager**pp = (IDataManager**)luaL_checkudata(L, 1, "woe.datamgr");
	if (pp==NULL)
	{
		return NULL;
	}
	else
	{
		return *pp;
	}
}

int dump(lua_State* L)
{
	IDataManager* pDataMgr = getUserData(L);
	if (pDataMgr)
	{
		std::cout<<"---------------------------------------"<<std::endl;
		std::cout<<"DataManager Size: "<<pDataMgr->size()<<std::endl;
	}
	return 0;
}

int put(lua_State* L)
{
	IDataManager* pDataMgr = getUserData(L);
	if (pDataMgr)
	{
		int nID = lua_tointeger(L, 2);
		int nGroupID = 0;
		if (lua_gettop(L)>2)
		{
			nGroupID = lua_tointeger(L, 3);
		}
		
		IData* pData = pDataMgr->get(nID, nGroupID);
		if (pData==NULL)
		{
			int nDataType = 0;
			if (lua_gettop(L)>3)
			{
				nDataType = lua_tointeger(L, 4);
			}
			//
			//	create different implementation of data base on nDataType
			//
			pData = new DataImp(nID, nGroupID);
			pDataMgr->set(pData);
		}

		DataLua::push(L, pData);
		return 1;
	}
	return 0;
}

int get(lua_State* L)
{
	IDataManager* pDataMgr = getUserData(L);
	if (pDataMgr)
	{
		int nID = lua_tointeger(L, 2);
		int nGroupID = 0;
		if (lua_gettop(L)>2)
		{
			nGroupID = lua_tointeger(L, 3);
		}

		IData* pData = pDataMgr->get(nID, nGroupID);
		if (pData)
		{
			DataLua::push(L, pData);
			return 1;
		}
	}
	return 0;
}



static const luaL_Reg datamgr_funcs[] = {
	{"dump", dump},
	{"get", get},
	{"put", put},
	{NULL, NULL}
};


int libaray(lua_State* L)
{
	luaL_newmetatable(L, "woe.datamgr");
	// fill member list into metatable
	luaL_register(L, NULL, datamgr_funcs);

	// metatable.__index = metatable
	lua_pushstring(L, "__index");
	lua_pushvalue(L, -2);
	lua_settable(L, -3);

	return 0;
}

}
